#include "napi/native_api.h"
#include "hilog/log.h"

#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include "errno.h"
#include <string.h>


napi_value OpenSerialPort(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value args[1];
    
    OH_LOG_INFO(LOG_APP, "OpenSerialPort device :  0"); 
    OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "SerialPort", "Native层打开串口: %{public}s", "/dev/ttyS0");
     napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
       
    OH_LOG_INFO(LOG_APP, "OpenSerialPort device :  1"); 
    
    char path[256];
    size_t path_len;
    OH_LOG_INFO(LOG_APP, "OpenSerialPort device :  2"); 
    napi_get_value_string_utf8(env, args[1], path, sizeof(path), &path_len);
    
    printf("Debug: Reached log point.\n");
    
//    OH_LOG_INFO(LOG_APP, "open device :  b:%{public}s. error", path); 
//    return NULL;
    OH_LOG_INFO(LOG_APP, "OpenSerialPort device :  3"); 
    
    int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1) {
     OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "SerialPort error", "errorno: %{public}s", strerror(errno));
    napi_throw_error(env, NULL, "Failed to open serial port");
        OH_LOG_INFO(LOG_APP, "open device :  b:%{public}s. error", path); 
    return NULL;
    }

    // 配置串口参数
    struct termios options;
    tcgetattr(fd, &options);
    cfsetispeed(&options, B9600);  // 波特率 9600
    cfsetospeed(&options, B9600);
    options.c_cflag |= (CLOCAL | CREAD);  // 本地连接，接收使能
    options.c_cflag &= ~PARENB;           // 无校验
    options.c_cflag &= ~CSTOPB;           // 1位停止位
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;               // 8位数据位
    tcsetattr(fd, TCSANOW, &options);
    OH_LOG_INFO(LOG_APP, "open device :  succeed"); 
//    
//    int fd = 15;
    napi_value result;
    napi_create_int32(env, fd, &result);
    return result;
}

napi_value ReadFromSerial(napi_env env, napi_callback_info info) {
  size_t argc = 1;
  napi_value args[1];
  napi_get_cb_info(env, info, &argc, args, NULL, NULL);

  int fd;
  napi_get_value_int32(env, args[1], &fd);

  char buffer[256];
  ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
  if (bytes_read < 0) {
    napi_throw_error(env, NULL, "Read error");
    return NULL;
  }

  napi_value result;
  napi_create_string_utf8(env, buffer, bytes_read, &result);
  return result;
}



static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);

    return sum;

}

napi_value WriteToSerial(napi_env env, napi_callback_info info) {
  size_t argc = 2;
  napi_value args[2];
  napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
  int fd;
  napi_get_value_int32(env, args[0], &fd);

  char data[256];
  size_t data_len;
  napi_get_value_string_utf8(env, args[1], data, sizeof(data), &data_len);

  ssize_t bytes_written = write(fd, data, data_len);
  if (bytes_written < 0) {
    napi_throw_error(env, NULL, "Write error");
    return NULL;
  }

  napi_value result;
  napi_create_int32(env, bytes_written, &result);
  return result;
}


static napi_value Subb(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 - value1, &sum);

    return sum;

}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "sub", nullptr, Subb, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "openSerialPort", nullptr, OpenSerialPort, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "readFromSerial", nullptr, ReadFromSerial, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "writeToSerial", nullptr, WriteToSerial, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
